/**
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　＞　　　＜　┃
 * ┃　　　　　　　┃
 * ┃...　⌒　...　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * ┃　　　┃
 * ┃　　　┃
 * ┃　　　┃
 * ┃　　　┃  神兽保佑
 * ┃　　　┃  代码无bug
 * ┃　　　┃
 * ┃　　　┗━━━┓
 * ┃　　　　　　　┣┓
 * ┃　　　　　　　┏┛
 * ┗┓┓┏━┳┓┏┛
 * ┃┫┫　┃┫┫
 * ┗┻┛　┗┻┛
 */

package com.handpay.zztong.hp.base.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import com.handpay.framework.ClientEngine;
import com.handpay.framework.NetEngineListener;
import com.handpay.framework.swiper.ApiSwiperFactory;
import com.handpay.framework.swiper.SwiperModel;
import com.handpay.framework.utils.ActivityStack;
import com.handpay.framework.utils.CommonUtils;
import com.handpay.zztong.hp.R;
import com.handpay.zztong.hp.ZZTApplication;
import com.handpay.zztong.hp.bean.ResponseBean;
import com.handpay.zztong.hp.log.HPLog;
import com.handpay.zztong.hp.trans.activity.VPOSActivity;
import com.handpay.zztong.hp.ui.CustomDialog;
import com.handpay.zztong.hp.ui.CustomProgressDialog;
import com.handpay.zztong.hp.utils.StatusBarUtil;

import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;

public abstract class BaseActivity extends AppCompatActivity implements NetEngineListener {
    // 进度条
    private static CustomProgressDialog progressDialog;
    protected static CustomDialog dialog;

    /**
     * 关闭ProgressDialog
     */
    public final void closeProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }

    /**
     * 关闭对话框
     */
    public void closeAlertDialog() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    public final void setProgressDialogMessage(CharSequence message) {
        if (progressDialog != null) {
            HPLog.i(HPLog.YL_TAG, "onProgressUpdate 2:" + message);
            progressDialog.setMessage(getString(R.string.uploaded_template, message));
        }
    }


    /**
     * 显示ProgressDialog
     *
     * @param title      标题
     * @param message    提示信息
     * @param style      样式
     * @param cancelable 是否能取消
     * @param max        最大值
     *
     */
    public void showProgressDialog(Context context, String title, String message, boolean cancelable, int style, int max,boolean isInVisible) {
        class RunnableShowProgressDialog implements Runnable {
            private Context context;
            private String title, message;
            private int style, max;
            private boolean cancelable;
            private  boolean isInVisible;
            public RunnableShowProgressDialog(Context context, String title, String message, int style, boolean cancelable, int max,boolean isInVisible) {
                this.context = context;
                this.title = title;
                this.message = message;
                this.style = style;
                this.cancelable = cancelable;
                this.max = max;
                this.isInVisible = isInVisible;
            }

            public void run() {
                if (progressDialog != null) {
                    progressDialog.dismiss();
                    progressDialog = null;
                }
                progressDialog = new CustomProgressDialog(context, style);
                if (isInVisible){
                    progressDialog.setInVisiable(true);
                }

                progressDialog.setMessage(message);
                progressDialog.setTitle(title);
                progressDialog.setProgressStyle(style);
                progressDialog.setCancelable(cancelable);
                progressDialog.setMax(max);
                progressDialog.show();
            }
        }
        this.runOnUiThread(new RunnableShowProgressDialog(context, title, message, style, cancelable, max,isInVisible));
    }

    public void showProgressDialog(Context context, String title, String message, boolean cancelable, int style) {
        showProgressDialog(context, title, message, cancelable, style, 100,false);
    }

    public void showProgressDialog(Context context, String title, String message, boolean cancelable) {
        showProgressDialog(context, title, message, cancelable, R.style.Theme_CustomDialog);
    }

    public void showProgressDialog(Context context, String title, String message) {
        showProgressDialog(context, title, message, false);
    }

    public void showProgressDialog(Context context, String message) {
        showProgressDialog(context, null, message);
    }

    public void showInsvisableProgressDialog(Context context, String message) {
        showProgressDialog(context, null, message, false, R.style.Theme_CustomDialog, 100,true);

//        showProgressDialog(context, null, message);
    }

    // 更新ProgressDialog的Progress值
    public void updateProgress(int value) {

        class RunnableProgressValue implements Runnable {
            private int value;

            public RunnableProgressValue(int value) {
                this.value = value;
            }

            @Override
            public void run() {
                if (progressDialog != null) {
                    if (value >= progressDialog.getMax()) {
                        closeProgressDialog();
                    } else {
                        progressDialog.setProgress(value);
                    }
                }
            }
        }
        this.runOnUiThread(new RunnableProgressValue(value));
    }

    // 对话框
    public final void showAlertDialog(Context context, String title, String message, boolean cancelable, String okString, OnClickListener oclOK, String cancelString, OnClickListener oclCancel, String middleButton, OnClickListener oclMiddle) {
        class RunnableShowAlertDialog implements Runnable {
            private Context context;
            private String title, message, neutral, mOKString, mCancelString;
            private boolean cancelable;
            private OnClickListener oclPositive, oclNeutral, oclNegative;
            private CustomDialog.Builder builder;

            public RunnableShowAlertDialog(Context context, String title, String message, boolean cancelable, String okString, OnClickListener oclOK, String cancelString, OnClickListener oclCancel, String middleButton, OnClickListener oclMiddle) {
                this.context = context;
                this.title = title;
                this.message = message;
                this.mOKString = okString;
                this.mCancelString = cancelString;
                this.cancelable = cancelable;
                oclPositive = oclOK;
                oclNegative = oclCancel;
                neutral = middleButton;
                oclNeutral = oclMiddle;
            }

            @Override
            public void run() {
                try {
                    if (dialog != null && dialog.isShowing()) {
                        if (builder == null) {
                            builder = setAlertBuilder(new CustomDialog.Builder(context));
                        } else {
                            builder = setAlertBuilder(builder);
                        }
                    } else {
                        builder = setAlertBuilder(new CustomDialog.Builder(context));
                    }
                    dialog = builder.create();
                    dialog.setCanceledOnTouchOutside(cancelable);
                    dialog.setCancelable(cancelable);
                    dialog.show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            /**
             * 设置Builder
             */
            private CustomDialog.Builder setAlertBuilder(CustomDialog.Builder builder) {
                builder.setTitle(title);
                builder.setMessage(CommonUtils.StringFilter(message));
                // 按钮文字为空时，不显示按钮
                if (TextUtils.isEmpty(mOKString)) {
                    builder.setPositiveButton(android.R.string.ok, oclPositive);
                } else {
                    builder.setPositiveButton(mOKString, oclPositive);
                }
                if (oclNeutral != null) {
                    builder.setNeutralButton(neutral, oclNeutral);
                }
                if (oclNegative != null) {
                    // 取消事件为空，认为是没有取消按钮
                    if (TextUtils.isEmpty(mCancelString)) {
                        builder.setNegativeButton(android.R.string.cancel, oclNegative);
                    } else {
                        builder.setNegativeButton(mCancelString, oclNegative);
                    }
                }
                return builder;
            }
        }
        this.runOnUiThread(new RunnableShowAlertDialog(context, title, message, cancelable, okString, oclOK, cancelString, oclCancel, middleButton, oclMiddle));
    }

    /**
     * @param context
     * @param title        标题
     * @param message      提示信息
     * @param cancelable   是否可取消
     * @param oclOK        确定事件
     * @param oclCancel    取消事件
     * @param middleButton 中间按钮文字
     * @param oclMiddle    中间按钮事件
     */
    public final void showAlertDialog(Context context, String title, String message, boolean cancelable, OnClickListener oclOK, OnClickListener oclCancel, String middleButton, OnClickListener oclMiddle) {
        showAlertDialog(context, title, message, cancelable, null, oclOK, null, oclCancel, middleButton, oclMiddle);
    }

    public final void showAlertDialog(Context context, String title, String message, boolean cancelable, OnClickListener oclOK, OnClickListener oclCancel) {
        showAlertDialog(context, title, message, cancelable, oclOK, oclCancel, null, null);
    }

    public final void showAlertDialog(Context context, String title, String message, boolean cancelable, OnClickListener oclOK) {
        showAlertDialog(context, title, message, cancelable, oclOK, null);
    }

    public final void showAlertDialog(Context context, String title, String message, boolean cancelable) {
        showAlertDialog(context, title, message, cancelable, null);
    }

    public final void showAlertDialog(Context context, String title, String message) {
        showAlertDialog(context, title, message, true, null);
    }

    public final void showAlertDialog(Context context, int title, int message) {
        showAlertDialog(context, getString(title), getString(message), true, null);
    }

    public final void showAlertDialog(Context context, String title) {
        showAlertDialog(context, title, null, true, null);
    }

    public final void showAlertDialog(Context context, String title, String message, boolean cancelable, String okString, OnClickListener oclOK, String cancleString, OnClickListener oclCancel) {
        showAlertDialog(context, title, message, cancelable, okString, oclOK, cancleString, oclCancel, null, null);
    }

    public final void showAlertDialog(Context context, int title) {
        showAlertDialog(context, getString(title));
    }

    public final void showAlertDialog(Context context, String title, OnClickListener oclOK) {
        showAlertDialog(context, title, null, false, oclOK);
    }

    // 退出
    protected boolean mIsMainPage = false; // 首页时判断按两次返回键退出
    private static boolean isExit = false; // 退出标记
    /**
     * 时间任务函数.不应该是实例变量，用于退出。只需要一个
     */
    private static Timer tExit = new Timer();
    private static TimerTask task = new TimerTask() {
        @Override
        public void run() {
            isExit = false;
        }
    };

    /**
     * 系统返回键盘的监听。以前只点击一次就退出，容易误点。现在给了一个提示在规定的时间以内点两次才能退出
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mIsMainPage) {
                if (isExit == false) {
                    isExit = true;
                    ClientEngine.showToast(this, getString(R.string.click_again_exit));
                    task = null;
                    task = new TimerTask() {
                        @Override
                        public void run() {
                            isExit = false;
                        }
                    };
                    tExit.schedule(task, 3000);
                } else {
                    ZZTApplication.getApp().exitApp();
                    System.exit(0);
                }
            } else {
                /*
                 * if(this instanceof VPOSActivity &&
				 * ApiSwiperFactory.getInstance().getSwiperModel() != null &&
				 * ApiSwiperFactory.getInstance().getSwiperModel() ==
				 * SwiperModel.ME368_BLUETOOTH){ HPLog.i("BbposM368",
				 * "屏蔽M35用户点击取消"); return true; }
				 */
                /**
                 * 联迪M36进行EMV过程中通过点击设备的取消按钮会触发onError回调，从而进行取消操作，解锁
                 * 如果手机端点击返回键只会调用stopOperation方法进行取消但是不会回调onError
                 * ，也就不会解锁，从而导致重新刷卡会等待很久(因为要等EMV超时)
                 */
                if (this instanceof VPOSActivity && ApiSwiperFactory.getInstance().getSwiperModel() != null && ApiSwiperFactory.getInstance().getSwiperModel() == SwiperModel.M36_BLUETOOTH) {
                    HPLog.i("Press Back", "屏蔽" + ApiSwiperFactory.getInstance().getSwiperModel().toString() + "用户点击取消");
                    return true;
                }
                goBack();
            }
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HPLog.d(HPLog.SSX_TAG,"currActivity------→"+this.getClass().getSimpleName());
//        ViewGroup contentFrameLayout = (ViewGroup) findViewById(Window.ID_ANDROID_CONTENT);
//        View parentView = contentFrameLayout.getChildAt(0);
//        if (parentView != null && Build.VERSION.SDK_INT >= 14) {
//            parentView.setFitsSystemWindows(true);
//        }
        setStatusBar();
        ActivityStack.getInstance().addActivity(this);
    }

    /***
     * 设置状态栏的颜色，可以自行重写此方法
     */
    public void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary), 0);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStack.getInstance().removeActivity(this);
    }

    /**
     * 返回键和标题栏返回按钮保持一致
     */
    protected void goBack() {
        finish();
    }

    /**
     * 返回到主菜单
     */
    protected void goToMain() {
    }

    public boolean isDataCompile;


    @Override
    public void callbackNetResponse(String action, Hashtable<String, Object> resp, boolean showAlert, boolean dataCompile) {
        this.isDataCompile = dataCompile;
        netResponse(action, resp, showAlert);
    }

    @Override
    public void callbackJsonNetResponse(String action, ResponseBean resp, boolean showAlert) {
        netJsonResponse(action, resp, showAlert);
    }

    //    @Override
//    /**
//     * Http请求响应结果
//     * 后台返回非0的responseCode或errMessage等错误信息，返回true
//     * 子类判断父类为true，直接return
//     */
    public boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert) {
        return netResponse(action, resp, showAlert, null);
    }

    public boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert) {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
                dialog.dismiss();
            }
        };
        return netJsonResponse(action, resp, showAlert, listener);
    }

    private String dealWebError(String errMsg) {
        if (errMsg.indexOf("M021") != -1) {
            return errMsg = "账账通开通失败";
        }
        // 显示系统异常，不应该提示用户后台信息
        // return getString(R.string.system_error);
        return errMsg;
    }

    /**
     * Http请求响应结果 后台返回非0的responseCode或errMessage等错误信息，返回true
     * 子类判断父类为true，直接return
     */
    //
    abstract boolean netResponse(String action, Hashtable<String, Object> resp, boolean showAlert, DialogInterface.OnClickListener on);

    abstract boolean netJsonResponse(String action, ResponseBean resp, boolean showAlert, DialogInterface.OnClickListener on);


    public boolean checkNetworkInfo() {
        ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
            // mobile 3G Data Network
            State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
            if (mobile == State.CONNECTED/* || mobile == State.CONNECTING */) {
                return true;
            }
        }

        if (conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null) {
            // wifi
            State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
            if (wifi == State.CONNECTED/* || wifi == State.CONNECTING */) {
                return true;
            }
        }

        return false;
    }

	/*
     * 对话框，不在onPause的时候关闭
	 * 
	 * @Override protected void onPause() { super.onPause(); if (dialog != null
	 * && dialog.isShowing()) { dialog.dismiss(); } }
	 */
}
